using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using FunMazeEngine;
using GameServer;
using System.Runtime.Serialization.Formatters;

namespace FunMazeClient
{
	public class frmRCleint : System.Windows.Forms.Form
	{
		private System.Windows.Forms.TextBox textBox1;
        private IMediator im = null;
        private EventsClass em = null;
        private GamePlayer playerid = null;
        private IGameClient client = null;
        private Mediator mm = new Mediator();
                
        private Game gameInfo = null;
        
        private Hashtable hsPrivateWindows = new Hashtable();   
        
		
		private System.ComponentModel.Container components = null;
        private TcpChannel chan = null;

        private Panel panel1;
        private Panel panel2;
        private TextBox serverbox;
        private TextBox playerbox;
        private Label servertext;
        private Label playertext;
        private Label treasuretext;
        private Label gridtext;
        private TextBox treasurebox;
        private TextBox gridbox;
        private Button createbutton;
        private Button joinbutton;
        private Button connectbutton;
        private Button eastbutton;
        private Button northbutton;
        private Button southbutton;
        private Button westbutton;
        private Button quitbutton;
        private Timer timer = new Timer();

        private string outputstring = "";

        private Button createserverbutton;

        public frmRCleint()
		{

			InitializeComponent();
//            timer.Interval = 500;
//            timer.Tick += new EventHandler(TimerOnTick);
//            timer.Enabled = true;
			
            //TcpChannel chan = new TcpChannel();
            //ChannelServices.RegisterChannel(chan);
            //remoteObject = (MazeServerObject)Activator.GetObject(typeof(MazeServerObject), "tcp://localhost:8080/HelloWorld");
            
            
                northbutton.Enabled = false;
                southbutton.Enabled = false;
                westbutton.Enabled = false;
                eastbutton.Enabled = false;
                joinbutton.Enabled = false;
                createbutton.Enabled = false;
                gridbox.Enabled = false;
                treasurebox.Enabled = false;
		}

        //[STAThread]
        //static void Main() 
        //{
        //    Application.Run(new frmRCleint());
        //}        	

        private void frmRCleint_Load(object sender, EventArgs e)
        {

        }

		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.panel1 = new System.Windows.Forms.Panel();
            this.createserverbutton = new System.Windows.Forms.Button();
            this.treasuretext = new System.Windows.Forms.Label();
            this.gridtext = new System.Windows.Forms.Label();
            this.treasurebox = new System.Windows.Forms.TextBox();
            this.gridbox = new System.Windows.Forms.TextBox();
            this.createbutton = new System.Windows.Forms.Button();
            this.joinbutton = new System.Windows.Forms.Button();
            this.connectbutton = new System.Windows.Forms.Button();
            this.servertext = new System.Windows.Forms.Label();
            this.playertext = new System.Windows.Forms.Label();
            this.serverbox = new System.Windows.Forms.TextBox();
            this.playerbox = new System.Windows.Forms.TextBox();
            this.panel2 = new System.Windows.Forms.Panel();
            this.quitbutton = new System.Windows.Forms.Button();
            this.eastbutton = new System.Windows.Forms.Button();
            this.northbutton = new System.Windows.Forms.Button();
            this.southbutton = new System.Windows.Forms.Button();
            this.westbutton = new System.Windows.Forms.Button();
            this.panel1.SuspendLayout();
            this.panel2.SuspendLayout();
            this.SuspendLayout();
            // 
            // textBox1
            // 
            this.textBox1.BackColor = System.Drawing.SystemColors.ButtonHighlight;
            this.textBox1.Enabled = false;
            this.textBox1.Location = new System.Drawing.Point(-1, 185);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.ReadOnly = true;
            this.textBox1.RightToLeft = System.Windows.Forms.RightToLeft.No;
            this.textBox1.Size = new System.Drawing.Size(443, 238);
            this.textBox1.TabIndex = 0;
            // 
            // panel1
            // 
            this.panel1.Controls.Add(this.createserverbutton);
            this.panel1.Controls.Add(this.treasuretext);
            this.panel1.Controls.Add(this.gridtext);
            this.panel1.Controls.Add(this.treasurebox);
            this.panel1.Controls.Add(this.gridbox);
            this.panel1.Controls.Add(this.createbutton);
            this.panel1.Controls.Add(this.joinbutton);
            this.panel1.Controls.Add(this.connectbutton);
            this.panel1.Controls.Add(this.servertext);
            this.panel1.Controls.Add(this.playertext);
            this.panel1.Controls.Add(this.serverbox);
            this.panel1.Controls.Add(this.playerbox);
            this.panel1.Location = new System.Drawing.Point(0, 1);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(673, 187);
            this.panel1.TabIndex = 1;
            this.panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.panel1_Paint);
            // 
            // createserverbutton
            // 
            this.createserverbutton.Location = new System.Drawing.Point(46, 123);
            this.createserverbutton.Name = "createserverbutton";
            this.createserverbutton.Size = new System.Drawing.Size(75, 23);
            this.createserverbutton.TabIndex = 11;
            this.createserverbutton.Text = "Create";
            this.createserverbutton.UseVisualStyleBackColor = true;
            this.createserverbutton.Click += new System.EventHandler(this.createserverbutton_Click);
            // 
            // treasuretext
            // 
            this.treasuretext.AutoSize = true;
            this.treasuretext.Location = new System.Drawing.Point(574, 13);
            this.treasuretext.Name = "treasuretext";
            this.treasuretext.Size = new System.Drawing.Size(52, 13);
            this.treasuretext.TabIndex = 10;
            this.treasuretext.Text = "Treasure:";
            // 
            // gridtext
            // 
            this.gridtext.AutoSize = true;
            this.gridtext.Location = new System.Drawing.Point(478, 13);
            this.gridtext.Name = "gridtext";
            this.gridtext.Size = new System.Drawing.Size(29, 13);
            this.gridtext.TabIndex = 9;
            this.gridtext.Text = "Grid:";
            // 
            // treasurebox
            // 
            this.treasurebox.Location = new System.Drawing.Point(574, 35);
            this.treasurebox.Name = "treasurebox";
            this.treasurebox.Size = new System.Drawing.Size(53, 20);
            this.treasurebox.TabIndex = 8;
            // 
            // gridbox
            // 
            this.gridbox.Location = new System.Drawing.Point(481, 35);
            this.gridbox.Name = "gridbox";
            this.gridbox.Size = new System.Drawing.Size(52, 20);
            this.gridbox.TabIndex = 7;
            // 
            // createbutton
            // 
            this.createbutton.Location = new System.Drawing.Point(574, 94);
            this.createbutton.Name = "createbutton";
            this.createbutton.Size = new System.Drawing.Size(87, 23);
            this.createbutton.TabIndex = 6;
            this.createbutton.Text = "Create Game";
            this.createbutton.UseVisualStyleBackColor = true;
            this.createbutton.Click += new System.EventHandler(this.createbutton_Click);
            // 
            // joinbutton
            // 
            this.joinbutton.Location = new System.Drawing.Point(471, 94);
            this.joinbutton.Name = "joinbutton";
            this.joinbutton.Size = new System.Drawing.Size(85, 23);
            this.joinbutton.TabIndex = 5;
            this.joinbutton.Text = "Join Game";
            this.joinbutton.UseVisualStyleBackColor = true;
            this.joinbutton.Click += new System.EventHandler(this.joinbutton_Click);
            // 
            // connectbutton
            // 
            this.connectbutton.Location = new System.Drawing.Point(141, 123);
            this.connectbutton.Name = "connectbutton";
            this.connectbutton.Size = new System.Drawing.Size(75, 23);
            this.connectbutton.TabIndex = 4;
            this.connectbutton.Text = "Connect";
            this.connectbutton.UseVisualStyleBackColor = true;
            this.connectbutton.Click += new System.EventHandler(this.connectbutton_Click);
            // 
            // servertext
            // 
            this.servertext.AutoSize = true;
            this.servertext.Location = new System.Drawing.Point(43, 70);
            this.servertext.Name = "servertext";
            this.servertext.Size = new System.Drawing.Size(72, 13);
            this.servertext.TabIndex = 3;
            this.servertext.Text = "Server Name:";
            // 
            // playertext
            // 
            this.playertext.AutoSize = true;
            this.playertext.Location = new System.Drawing.Point(43, 9);
            this.playertext.Name = "playertext";
            this.playertext.Size = new System.Drawing.Size(70, 13);
            this.playertext.TabIndex = 2;
            this.playertext.Text = "Player Name:";
            // 
            // serverbox
            // 
            this.serverbox.Location = new System.Drawing.Point(46, 97);
            this.serverbox.Name = "serverbox";
            this.serverbox.Size = new System.Drawing.Size(170, 20);
            this.serverbox.TabIndex = 1;
            // 
            // playerbox
            // 
            this.playerbox.Location = new System.Drawing.Point(46, 36);
            this.playerbox.Name = "playerbox";
            this.playerbox.Size = new System.Drawing.Size(170, 20);
            this.playerbox.TabIndex = 0;
            // 
            // panel2
            // 
            this.panel2.Controls.Add(this.quitbutton);
            this.panel2.Controls.Add(this.eastbutton);
            this.panel2.Controls.Add(this.northbutton);
            this.panel2.Controls.Add(this.southbutton);
            this.panel2.Controls.Add(this.westbutton);
            this.panel2.Location = new System.Drawing.Point(439, 162);
            this.panel2.Name = "panel2";
            this.panel2.Size = new System.Drawing.Size(234, 264);
            this.panel2.TabIndex = 0;
            // 
            // quitbutton
            // 
            this.quitbutton.Location = new System.Drawing.Point(147, 223);
            this.quitbutton.Name = "quitbutton";
            this.quitbutton.Size = new System.Drawing.Size(75, 23);
            this.quitbutton.TabIndex = 4;
            this.quitbutton.Text = "Quit";
            this.quitbutton.UseVisualStyleBackColor = true;
            this.quitbutton.Click += new System.EventHandler(this.quitbutton_Click);
            // 
            // eastbutton
            // 
            this.eastbutton.Location = new System.Drawing.Point(147, 78);
            this.eastbutton.Name = "eastbutton";
            this.eastbutton.Size = new System.Drawing.Size(50, 50);
            this.eastbutton.TabIndex = 3;
            this.eastbutton.Text = "East";
            this.eastbutton.UseVisualStyleBackColor = true;
            this.eastbutton.Click += new System.EventHandler(this.eastbutton_Click);
            // 
            // northbutton
            // 
            this.northbutton.Location = new System.Drawing.Point(89, 23);
            this.northbutton.Name = "northbutton";
            this.northbutton.Size = new System.Drawing.Size(51, 49);
            this.northbutton.TabIndex = 2;
            this.northbutton.Text = "North";
            this.northbutton.UseVisualStyleBackColor = true;
            this.northbutton.Click += new System.EventHandler(this.northbutton_Click);
            // 
            // southbutton
            // 
            this.southbutton.Location = new System.Drawing.Point(89, 138);
            this.southbutton.Name = "southbutton";
            this.southbutton.Size = new System.Drawing.Size(51, 49);
            this.southbutton.TabIndex = 1;
            this.southbutton.Text = "South";
            this.southbutton.UseVisualStyleBackColor = true;
            this.southbutton.Click += new System.EventHandler(this.southbutton_Click);
            // 
            // westbutton
            // 
            this.westbutton.Location = new System.Drawing.Point(32, 78);
            this.westbutton.Name = "westbutton";
            this.westbutton.Size = new System.Drawing.Size(51, 49);
            this.westbutton.TabIndex = 0;
            this.westbutton.Text = "West";
            this.westbutton.UseVisualStyleBackColor = true;
            this.westbutton.Click += new System.EventHandler(this.westbutton_Click);
            // 
            // frmRCleint
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(709, 470);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.panel2);
            this.Controls.Add(this.panel1);
            this.Name = "frmRCleint";
            this.Text = "RemoteClient";
            this.panel1.ResumeLayout(false);
            this.panel1.PerformLayout();
            this.panel2.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion
  

		private void button1_Click(object sender, System.EventArgs e)
		{
			//remoteObject.SetMessage(textBox1.Text);
		}
//		private void button1_Click(object sender, System.EventArgs e)
//		{
//			remoteObject.SetMessage(textBox1.Text);
//		}

		private void textBox1_TextChanged(object sender, System.EventArgs e)
		{
			//remoteObject.SetMessage(textBox1.Text);
		}
//		private void textBox1_TextChanged(object sender, System.EventArgs e)
//		{
//			remoteObject.SetMessage(textBox1.Text);
//		}


//        void TimerOnTick(object obj, EventArgs ea)
//        {
/*            if (chatClient != null)
            {
                string[] arrData;
                //chatClient.GetData(out arrData);

                //for (int i = 0; i < arrData.Length; i++)
                //    listData.Items.Add(arrData[i]);

<<<<<<< .mine
                //listData.SelectedIndex = listData.Items.Count - 1;
=======
                //listData.SelectedIndex = listData.Items.Count - 1;
            }*/
 //       }

        private void quitbutton_Click(object sender, EventArgs e)
        {
            im.ExitGame(client);
            Close();
        }

        private void westbutton_Click(object sender, EventArgs e)
        {
            try
            {
                im = new Mediator();
                if (mm.PlayerMoveWest(client))
                {
                    int row, column;
                    gameInfo.GameMap.GetRowColumnLocation(client.Player.Location, out row, out column);
                    textBox1.Text = textBox1.Text + "\r\nYou moved West. \r\nYou are currently at (" + Convert.ToString(row) + "," + Convert.ToString(column) + ").\r\nYou have " + Convert.ToString(client.Player.TotalCollectedTreasure) + " treasures";
                }

                else
                {
                    textBox1.Text = textBox1.Text + "\r\nMove failed. You must have either hit the wall or knocked into someone else!";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }

        private void southbutton_Click(object sender, EventArgs e)
        {
            try
            {
                im = new Mediator();
                if (mm.PlayerMoveSouth(client))
                {
                    int row, column;
                    gameInfo.GameMap.GetRowColumnLocation(client.Player.Location, out row, out column);
                    textBox1.Text = textBox1.Text + "\r\nYou moved South. \r\nYou are currently at (" + Convert.ToString(row) + "," + Convert.ToString(column) + ").\r\nYou have " + Convert.ToString(client.Player.TotalCollectedTreasure) + " treasures";
                }

                else
                {
                    textBox1.Text = textBox1.Text + "\r\nMove failed. You must have either hit the wall or knocked into someone else!";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }

        private void eastbutton_Click(object sender, EventArgs e)
        {
            try
            {
                im = new Mediator();
                if (mm.PlayerMoveEast(client))
                {
                    int row, column;
                    gameInfo.GameMap.GetRowColumnLocation(client.Player.Location, out row, out column);
                    textBox1.Text = textBox1.Text + "\r\nYou moved East. \r\nYou are currently at (" + Convert.ToString(row) + "," + Convert.ToString(column) + ").\r\nYou have " + Convert.ToString(client.Player.TotalCollectedTreasure) + " treasures";
                }

                else
                {
                    textBox1.Text = textBox1.Text + "\r\nMove failed. You must have either hit the wall or knocked into someone else!";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }

        private void northbutton_Click(object sender, EventArgs e)
        {
            try
            {
                im = new Mediator();
                if (mm.PlayerMoveNorth(client))
                {
                    int row, column;
                    gameInfo.GameMap.GetRowColumnLocation(client.Player.Location, out row, out column);
                    textBox1.Text = textBox1.Text + "\r\nYou moved North. \r\nYou are currently at (" + Convert.ToString(row) + "," + Convert.ToString(column) + ").\r\nYou have " + Convert.ToString(client.Player.TotalCollectedTreasure) + " treasures";
                }

                else
                {
                    textBox1.Text = textBox1.Text + "\r\nMove failed. You must have either hit the wall or knocked into someone else!";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }

        private void createbutton_Click(object sender, EventArgs e)
        {
            try
            {
                im = new Mediator();
                //if (this.im != null)
                //{
                    int grid = int.Parse(gridbox.Text);
                    int treasure = int.Parse(treasurebox.Text);
                    if (grid <= 0 || treasure <= 0)
                    {
                        textBox1.Text = "Grid Size and number of Treasure must be larger than 0.";
                    }
                    else
                    {
                        if (mm.CreateGame(client, grid, treasure))
                        {
                            gameInfo = mm.Game;
                            gridbox.Enabled = false;
                            treasurebox.Enabled = false;
                            createbutton.Enabled = false;
                            outputstring = playerbox.Text + " has created a game in server " + serverbox.Text + " of size " + gridbox.Text + " with " + treasurebox.Text + " treasures! \r\n haha";
                            textBox1.Text = textBox1.Text + "\r\n" +outputstring;
                            northbutton.Enabled = true;
                            southbutton.Enabled = true;
                            westbutton.Enabled = true;
                            eastbutton.Enabled = true;
                        }
                        else
                        {
                            outputstring = " \r\ngrid:" + Convert.ToString(grid) + " \r\ntreasure:" + Convert.ToString(treasure) + "\r\nGame Creation failed";
                            textBox1.Text = outputstring;
                        }
                    }
                //}
                //else { textBox1.Text = "im failed"; }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }

        private void joinbutton_Click(object sender, EventArgs e)
        {
            try {
                if (im.JoinGame(client))
                {
                    joinbutton.Enabled = false;
                    textBox1.Text = playerbox.Text +"Joined Game!";
                                        northbutton.Enabled = true;
                                        southbutton.Enabled = true;
                                        westbutton.Enabled = true;
                                        eastbutton.Enabled = true;
                }
                else
                {
                    textBox1.Text = "Game started, unable to join game";
                }
                    
                }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
            // join game
        }

        private void connectbutton_Click(object sender, EventArgs e)
        {
            try
            {
                client = new EventsClass();
                em = new EventsClass();
                this.im = (IMediator)Activator.GetObject(typeof(IMediator), serverbox.Text);
                //this.em.GameUpdateHandler += new GameUpdate(this.GameUpdate);
                this.em.WelComeMessageHandler += new WelComeMessage(this.WelcomeMessage);
                

                if (gameInfo.NameChecker(playerbox.Text))
                {
                    textBox1.Text = "Someone is using that player name";
                }
                else if (playerbox.Text == "")
                {
                    textBox1.Text = "Please enter a player name";
                }
                else if (serverbox.Text == "")
                {
                    textBox1.Text = "Please enter a server name";
                }
                else
                {
                    client.Player = new GamePlayer(playerbox.Text);
                    im.JoinGame(client);

                    if (!im.GameExists())
                    {
                        createbutton.Enabled = true;
                        gridbox.Enabled = true;
                        treasurebox.Enabled = true;
                    }
                    else
                    {
                        joinbutton.Enabled = true;
                    }
                    createserverbutton.Enabled = false;
                    connectbutton.Enabled = false;
                    playerbox.Enabled = false;
                    serverbox.Enabled = false;
                    textBox1.Text = playerbox.Text + " has joined Server " + serverbox.Text + "!";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
        
        private void gamestart()
        {
            northbutton.Enabled = true;
            southbutton.Enabled = true;
            westbutton.Enabled = true;
            eastbutton.Enabled = true;

            int row, column;
            gameInfo.GameMap.GetRowColumnLocation(client.Player.Location, out row, out column);
            textBox1.Text = "You are currently at (" + row + "," + column + ").";
        }

        private void createserverbutton_Click(object sender, EventArgs e)
        {
            client = new EventsClass();
            em = new EventsClass();

            BinaryClientFormatterSinkProvider bcfs = new BinaryClientFormatterSinkProvider();
            BinaryServerFormatterSinkProvider bsfs = new BinaryServerFormatterSinkProvider();
            bsfs.TypeFilterLevel = TypeFilterLevel.Full;

            IDictionary id = new Hashtable();
            id = new Hashtable();
            id["port"] = 0;
            id["typeFilterLevel"] = TypeFilterLevel.Full;
            id["name"] = System.Guid.NewGuid().ToString();

            TcpChannel tcc = new TcpChannel(id, bcfs, bsfs);
            ChannelServices.RegisterChannel(tcc);
            this.im = (IMediator)Activator.GetObject(typeof(IMediator), serverbox.Text);
            id.Clear();
            id = null;

            textBox1.Text = "Server Created";

            client.Player = new GamePlayer(playerbox.Text);

            textBox1.Text = "Player created";

            createbutton.Enabled = true;
            gridbox.Enabled = true;
            treasurebox.Enabled = true;

        }

        void GameUpdate(Game gameInfo)
        {
            this.gameInfo = gameInfo;
            this.textBox1.Clear();
            foreach (IGameClient client in gameInfo.gamePlayerList)
                this.textBox1.Text = this.textBox1.Text + "\r\n" + client.Player.Name + "\t\t" +Convert.ToString(client.Player.TotalCollectedTreasure);
        }
        void WelcomeMessage(string message)
        {
            this.textBox1.Text = this.textBox1.Text+"\r\n"+message;
        }
        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

       
    }
}
